<template>
    <div class="app-container">
        <!-- 搜索区域 -->
        <el-card class="search-card" v-show="showSearch">
            <el-form :model="queryParams" ref="queryForm">
                <el-row :gutter="20">
                    <el-col :span="6">
                        <el-form-item label="供应商名称" prop="supplierName">
                            <el-input v-model="queryParams.supplierName" placeholder="请输入供应商名称" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="供应商类型" prop="supplierType">
                            <el-select v-model="queryParams.supplierType" placeholder="请选择供应商类型" clearable>
                                <el-option v-for="item in supplierTypeOptions" :key="item.id" :label="item.name"
                                    :value="item.id" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="状态" prop="supplierStatus">
                            <el-select v-model="queryParams.supplierStatus" placeholder="请选择状态" clearable>
                                <el-option label="启用" value="1" />
                                <el-option label="禁用" value="0" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6" class="search-btn">
                        <el-button type="primary" @click="handleQuery">搜索</el-button>
                        <el-button @click="resetQuery">重置</el-button>
                    </el-col>
                </el-row>
            </el-form>
        </el-card>

        <!-- 操作按钮区域 -->
        <el-card style="margin-top: 20px;">

            <el-row :gutter="10" class="mb8">
                <el-col :span="1.5">
                    <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
                </el-col>
                <el-col :span="1.5">
                    <el-button type="danger" plain icon="Delete" :disabled="multiple"
                        @click="handleBatchDelete">删除</el-button>
                </el-col>
                <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
            </el-row>
            <!-- 表格区域 -->
            <el-table v-loading="loading" :data="supplierList" @selection-change="handleSelectionChange"
                style="width: 100%; margin-top: 20px;">
                <el-table-column type="selection" width="55" align="center" />
                <!-- <el-table-column prop="supplierId" label="供应商ID" align="center" /> -->
                <el-table-column type="index" label="序号" width="55" align="center" />
                <el-table-column prop="supplierName" label="供应商名称" align="center" />
                <el-table-column prop="supplierType" label="供应商类型" align="center">
                    <template #default="{ row }">
                        <el-tag>{{supplierTypeOptions.find(item => item.id == row.supplierType)?.name}}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="supplierStatus" label="状态" align="center" width="80">
                    <template #default="{ row }">
                        <el-tag type="success" v-if="row.supplierStatus == '1'">启用</el-tag>
                        <el-tag type="error" v-else>禁用</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="createTime" label="创建时间" align="center" width="180" />
                <el-table-column label="操作" align="center" width="180">
                    <template #default="{ row }">
                        <el-button type="text" size="small" @click="handleEdit(row)">
                            编辑
                        </el-button>
                        <el-button type="text" size="small" @click="handleDelete(row)">
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页区域 -->
            <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
                v-model:limit="queryParams.pageSize" @pagination="getList" />
        </el-card>

        <!-- 添加/编辑对话框 -->
        <el-dialog :title="dialog.title" v-model="dialog.visible" width="600px" append-to-body>
            <el-form ref="supplierForm" :model="form" :rules="rules" label-width="100px">
                <el-form-item label="供应商名称" prop="supplierName">
                    <el-input v-model="form.supplierName" placeholder="请输入供应商名称" />
                </el-form-item>
                <el-form-item label="供应商类型" prop="supplierType">
                    <el-select v-model="form.supplierType" placeholder="请选择供应商类型" clearable>
                        <el-option v-for="item in supplierTypeOptions" :key="item.id" :label="item.name"
                            :value="+item.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="状态" prop="supplierStatus">
                    <el-radio-group v-model="form.supplierStatus">
                        <el-radio label="1" :value="1">启用</el-radio>
                        <el-radio label="0" :value="0">禁用</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="dialog.visible = false">取 消</el-button>
                <el-button type="primary" @click="submitForm">确 定</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
    exportSupplierList,
    getSupplierTypeDict,
    listSupplierInfo,
    getSupplierDetail,
    addSupplierInfo,
    updateSupplierInfo,
    deleteSupplierInfo
} from '@/api/basic/message/supplierManage';

const showSearch = ref(true);

// 数据状态
const loading = ref(false)
const supplierList = ref([])
const total = ref(0)
const supplierTypeOptions = ref([])
const selectedRows = ref([])

// 查询参数
const queryParams = reactive({
    pageNum: 1,
    pageSize: 10,
    supplierName: '',
    supplierType: '',
    supplierStatus: ''
})

// 表单数据
const form = ref({
    supplierId: undefined,
    supplierName: '',
    supplierType: '',
    contactPerson: '',
    contactPhone: '',
    supplierStatus: '1',
    remark: ''
})

// 对话框状态
const dialog = reactive({
    visible: false,
    title: ''
})

// 表单验证规则
const rules = reactive({
    supplierName: [
        { required: true, message: '供应商名称不能为空', trigger: 'blur' }
    ],
    supplierType: [
        { required: true, message: '供应商类型不能为空', trigger: 'change' }
    ],
    contactPerson: [
        { required: true, message: '联系人不能为空', trigger: 'blur' }
    ],
    contactPhone: [
        { required: true, message: '联系电话不能为空', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
    ]
})


// 获取供应商类型选项
const getSupplierTypeOptions = async () => {
    try {
        const res = await getSupplierTypeDict()
        supplierTypeOptions.value = res.data;
    } catch (error) {
        console.error('获取供应商类型失败:', error)
    }
}

// 获取供应商列表
const getList = async () => {
    loading.value = true
    try {
        const res = await listSupplierInfo(queryParams)
        supplierList.value = res.rows;
        total.value = res.total;
    } catch (error) {
        console.error('获取供应商列表失败:', error)
    } finally {
        loading.value = false
    }
}

// 搜索
const handleQuery = () => {
    queryParams.pageNum = 1;
    getList();
    getSupplierTypeOptions();
}

// 重置
const resetQuery = () => {
    queryParams.pageNum = 1
    queryParams.supplierName = ''
    queryParams.supplierType = ''
    queryParams.supplierStatus = ''
    getList()
}

// 多选
const handleSelectionChange = (selection) => {
    selectedRows.value = selection.map(item => item.supplierId)
}

// 新增
const handleAdd = () => {
    dialog.visible = true
    dialog.title = '添加供应商'
    form.value = {
        supplierId: undefined,
        supplierName: '',
        supplierType: '',
        contactPerson: '',
        contactPhone: '',
        supplierStatus: '1',
        remark: ''
    }
}

// 编辑
const handleEdit = async (row) => {
    try {
        const res = await getSupplierDetail(row.supplierId)
        form.value = res.data;
        dialog.visible = true;
        dialog.title = '修改供应商'
    } catch (error) {
        console.error('获取供应商详情失败:', error)
    }
}

// 提交表单
const submitForm = async () => {
    try {
        if (form.value.supplierId) {
            await updateSupplierInfo(form.value)
            ElMessage.success('修改成功')
        } else {
            await addSupplierInfo(form.value)
            ElMessage.success('添加成功')
        }
        dialog.visible = false
        getList()
    } catch (error) {
        console.error('操作失败:', error)
    }
}

// 删除
const handleDelete = (row) => {
    ElMessageBox.confirm('确认删除该供应商吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        await deleteSupplierInfo(row.supplierId)
        ElMessage.success('删除成功')
        getList()
    }).catch(() => { })
}

// 批量删除
const handleBatchDelete = () => {
    ElMessageBox.confirm(`确认删除选中的${selectedRows.value.length}条记录吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        await Promise.all(selectedRows.value.map(id => deleteSupplierInfo(id)))
        ElMessage.success('删除成功')
        getList()
    }).catch(() => { })
}

// 导出
const handleExport = async () => {
    try {
        await ElMessageBox.confirm('确认导出所有供应商数据?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })

        loading.value = true
        const data = await exportSupplierList(queryParams)
        const blob = new Blob([data], { type: 'application/vnd.ms-excel' })
        const link = document.createElement('a')
        link.href = URL.createObjectURL(blob)
        link.download = '供应商列表.xlsx'
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
    } catch (error) {
        if (error !== 'cancel') {
            console.error('导出失败:', error)
        }
    } finally {
        loading.value = false
    }
}

getList(); // 初始化数据
getSupplierTypeOptions(); // 类型下拉列表

</script>

<style scoped>
.search-card :deep(.el-form-item) {
    margin-bottom: 0px;
}

.search-btn {
    text-align: right;
}
</style>